<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Utils\ModelOperatorTrait;
use Illuminate\Validation\Rule;
use App\Exports\SnapAbnormalExport;
use Maatwebsite\Excel\Facades\Excel;

class SnapAbnormalController extends Controller
{
    use ModelOperatorTrait;

    protected function model(){
        return app(\App\Models\SnapAbnormal::class);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $query = $this->queryModel(request()->input());

        if(isset(request()->start_time)){
            $query = $query->where('system_date','>=',request()->start_time);
            $query = $query->where('system_date','<=',request()->end_time);
        }

        $query = $query->orderBy('system_date','DESC');

        if(request()->has('page')){
            return formatJsonResponse($query->paginate());
        }
        else{
            return formatJsonResponse($query->get());
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $rules = [
            'handling_situation' => ['required',Rule::in(array_keys($this->model()::$HANDLING_SITUATION))]
        ];

        $this->validate($rules);

        $this->updateModel($id,$request->all());

        return formatJsonResponse();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    public function export(Request $request){
        return Excel::download(new SnapAbnormalExport($request->all()), '抓拍异常记录'. time() .'.xlsx');
    }

    public function handlingSituation(){
        return formatJsonResponse(itemOption($this->model()::$HANDLING_SITUATION));
    }
}
